/*
 * 版权所有 (C) 2015 知启蒙(ZHIQIM) 保留所有权利。[遇见知启蒙，邂逅框架梦]
 * 
 * https://zhiqim.org/project/zhiqim_framework/zhiqim_httpd.htm
 *
 * Zhiqim Httpd is licensed under Mulan PSL v2.
 * You can use this software according to the terms and conditions of the Mulan PSL v2.
 * You may obtain a copy of Mulan PSL v2 at:
 *          http://license.coscl.org.cn/MulanPSL2
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PSL v2 for more details.
 */
package org.zhiqim.httpd;

import java.net.URL;
import java.net.URLClassLoader;

/**
 * HTTP 上下文环境的ClassLoader
 *
 * @version v1.0.0 @author zouzhigang 2014-3-21 新建与整理
 */
public class HttpContextLoader extends URLClassLoader
{
    private static final String[] _SYSTEM_CLASSES_ = new String [] {"java.","javax.xml.","org.xml.","org.w3c.","org.zhiqim."};
    
    private ClassLoader _parent;
    
    public HttpContextLoader(ClassLoader parent)
    {
        super(new URL[0], parent);
        this._parent = parent;
    }
    
    public Class<?> loadClass(String name) throws ClassNotFoundException
    {
        return loadClass(name, false);
    }
    
    protected Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundException
    {
        Class<?> c = findLoadedClass(name);
        if (c != null)
            return c;
        
        ClassNotFoundException ex= null;
        try{c = this.findClass(name);}catch (ClassNotFoundException e){ex = e;}
        
        if (c == null && _parent != null)
            try{c = _parent.loadClass(name);}catch (ClassNotFoundException e){ex = e;}
        
        if (c == null)
            throw ex;

        if (resolve)
            resolveClass(c);

        return c;
    }
    
    public URL getResource(String name)
    {
        URL url = null;
        boolean triedParent = false;
        if (isSystemPath(name))
        {
            triedParent = true;
            url = _parent.getResource(name);
        }
        
        if (url == null)
        {
            url = this.findResource(name);
            if (url == null && name.startsWith("/"))
                url = this.findResource(name.substring(1));
        }
        
        if (url == null && !triedParent)
            url = _parent.getResource(name);
        
        return url;
    }
    
    /** 是否指定为系统路径 */
    public boolean isSystemPath(String name)
    {
        name = name.replace('/','.');
        while(name.startsWith("."))
            name = name.substring(1);

        for (String c : _SYSTEM_CLASSES_)
        {
            if (c.endsWith("."))
            {//类前缀
                if (name.startsWith(c))
                    return true;
            }
            else if (name.equals(c))
            {//类全称
                return true;
            }
        }
        
        return false;
    }
}
